<?php
// +----------------------------------------------------------------------
// | LikeShop100%开源免费商用电商系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | 商业版本务必购买商业授权，以免引起法律纠纷
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | Gitee下载：https://gitee.com/likeshop_gitee/likeshop
// | 访问官网：https://www.likemarket.net
// | 访问社区：https://home.likemarket.net
// | 访问手册：http://doc.likemarket.net
// | 微信公众号：好象科技
// | 好象科技开发团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------

// | Author: LikeShopTeam
// +----------------------------------------------------------------------
namespace app\api\logic;

use app\api\model\Goods;
use app\common\logic\UserLogCopyLogic;
use app\common\model\Footprint;
use app\common\server\ConfigServer;
use think\Db;
use think\facade\Hook;

class GoodsLogic
{
    //商品列表
    public static function getGoodsList($post, $page, $size)
    {
        $where = [];
        $order = [];
        $where[] = ['g.del', '=', 0];
        $where[] = ['g.status', '=', 2];
        //商户筛选
        if (isset($post['supplier_id']) && $post['supplier_id']) {
            $where[] = ['g.supplier_id', '=', $post['supplier_id']];
        }

        //品牌筛选
        if (isset($post['brand_id']) && $post['brand_id']) {
            $where[] = ['g.brand_id', '=', $post['brand_id']];
        }
        //分类筛选
        if (isset($post['category_id']) && $post['category_id']) {
            $where[] = ['g.first_category_id', '=', $post['category_id']];
        }
//        //品牌筛选
//        if (isset($get['second_category_id']) && $get['second_category_id']) {
//            $where[] = ['g.second_category_id', '=', $get['second_category_id']];
//        }
        //价格区间筛选
        if (isset($post['start_price']) && $post['start_price']) {
            $where[] = ['g.good_price', '>=', $post['start_price']];
        }
        if (isset($post['end_price']) && $post['end_price']) {
            $where[] = ['g.good_price', '<=', $post['end_price']];
        }
        //佣金比例筛选
        if (isset($post['start_commission']) && $post['start_commission']) {
            $where[] = ['g.commission', '>=', $post['start_commission']];
        }
        if (isset($post['end_commission']) && $post['end_commission']) {
            $where[] = ['g.commission', '<=', $post['end_commission']];
        }
        // 平台
        if (isset($post['platform']) && $post['platform']) {
            $where[] = ['g.platform', 'like', '%' . $post['platform'] . '%'];
        }
        // 福利
        if (isset($post['welfare']) && $post['welfare']) {
            $where[] = ['g.welfare', 'like', '%' . $post['welfare'] . '%'];
        }

        // 福利
        if (isset($post['coupon']) && $post['coupon'] == 1) {
            $where[] = ['g.coupon', '>', 0];
        }

        //关键词搜索
        if (isset($post['name']) && $post['name']) {
            $where[] = ['g.name', 'like', '%' . $post['name'] . '%'];
            // if($user_id){//记录关键词
            //     self::recordKeyWord(trim($get['keyword']),$user_id);
            // }
        }
        //佣金排序
        if (isset($post['commission']) && $post['commission']) {
            $order['commission'] = $post['commission'] ?? 'desc';
        }

        //价格排序
        if (isset($post['good_price']) && $post['good_price']) {
            $order['good_price'] = $post['good_price'] ?? 'desc';
        }

        //时间排序
        if (isset($post['create_time']) && $post['create_time']) {
            $order['create_time'] = $post['create_time'] ?? 'desc';
        }

        //精选排序
        if (isset($post['sort']) && $post['sort']) {
            $order['sort'] = $post['sort'] ?? 'desc';
        }

        $order = 'g.sort desc,g.id desc';

        $goods_count = Db::name('goods')->alias("g")
            ->where($where)
            ->count();

        $goods_list = Db::name('goods')
            ->alias("g")
            ->leftJoin("supplier s", "g.supplier_id = s.id")
            ->field('g.*,s.platform as supplier_platform')
            ->where($where)
            ->page($page, $size)
            ->order($order)
            ->select();
        $more = is_more($goods_count, $page, $size);  //是否有下一页

        foreach ($goods_list as $k => $v) {
            $goods_list[$k]['create_time'] = date("Y-m-d H:i", $v['create_time']);
            $goods_list[$k]['update_time'] = !empty($v['create_time']) ? date("Y-m-d H:i", $v['create_time']) : NULL;

            if (!empty($v['platform'])) {
                $goods_list[$k]['platform'] = $v['platform'];
            }

            if (!empty($v['welfare'])) {
                $goods_list[$k]['welfare'] = implode(',', json_decode($v['welfare'], true));
            }

            if ($v['supplier_platform']) {
                $goods_list[$k]['supplier_platform'] = implode(',', json_decode($v['supplier_platform'], true));
            }

        }

        $data = [
            'list' => $goods_list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $goods_count,
            'more' => $more
        ];
        return $data;
    }


    /**
     * 商户商品列表
     * @param $supplier_id
     * @param $get
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getMyGoodsList($supplier_id, $get, $page, $size)
    {
        $where = [];
        $order = [];
        $where[] = ['g.del', '=', 0];
        if (!empty($supplier_id)) {
            $where[] = ['supplier_id', '=', $supplier_id];
        }

        //品牌筛选
            if (isset($get['brand_id']) && $get['brand_id']) {
            $where[] = ['g.brand_id', '=', $get['brand_id']];
        }
        //分类筛选
        if (isset($get['category_id']) && $get['category_id']) {
            $where[] = ['g.category_id', '=', $get['category_id']];
        }
        //二级分类筛选
        if (isset($get['second_category_id']) && $get['second_category_id']) {
            $where[] = ['g.second_category_id', '=', $get['second_category_id']];
        }
        //价格区间筛选
        if (isset($get['start_price']) && $get['start_price']) {
            $where[] = ['g.good_price', '<=', $get['start_price']];
        }
        if (isset($get['end_price']) && $get['end_price']) {
            $where[] = ['g.good_price', '=', $get['end_price']];
        }
        //佣金比例筛选
        if (isset($get['start_commission']) && $get['start_commission']) {
            $where[] = ['g.commission', '=', $get['start_commission']];
        }
        if (isset($get['end_commission']) && $get['end_commission']) {
            $where[] = ['g.commission', '=', $get['end_commission']];
        }
        //关键词搜索
        if (isset($get['name']) && $get['name']) {
            $where[] = ['g.name', 'like', '%' . $get['name'] . '%'];
        }
        // '商品状态:0下架；1提交(上架审核)；2正常；3未通过；4作废()'
        if (isset($get['status']) && $get['status']) {
            switch ($get['status']) {
                // 1 审核状态
                case 1:
                    $where[] = ['status', 'in', [1, 3]];
                    break;
                // 2 已发布
                case 2:
                    $where[] = ['status', '=', 2];
                    break;
                // 3 已下架
                case 3:
                    $where[] = ['status', 'in', [0, 4]];
                    break;
            }
        }

        // //销量排序
        // if(isset($get['sales_sum']) && $get['sales_sum']){
        //     $order['sales_sum'] = $get['sales_sum'];
        // }
        //价格排序
//        if (isset($get['good_price']) && $get['good_price']) {
//            $order['good_price'] = $get['good_price'];
//        }

        $order = 'sort desc,id desc';
//        $order['id'] = 'desc';

        $goods_count = Db::name('goods')->alias("g")
            ->where($where)
            ->count();

        $goods_list = Db::name('goods')
            ->alias("g")
            ->field('g.*')
            ->where($where)
            ->page($page, $size)
            ->order($order)
            ->select();

        $more = is_more($goods_count, $page, $size);  //是否有下一页


        foreach ($goods_list as $k => $v) {
            $goods_list[$k]['create_time'] = date("Y-m-d H:i", $v['create_time']);
            $goods_list[$k]['update_time'] = !empty($v['create_time']) ? date("Y-m-d H:i", $v['create_time']) : NULL;
            if ($v['status'] == 3) {
                $examine = UserLogCopyLogic::getRemarks(["id" => $v['id'], "type" => 1,]);
                if ($examine) {
                    $goods_list[$k]['examine'] = $examine;
                }
            }
            if ($v['status'] == 4) {
                $examine = UserLogCopyLogic::getRemarks(["id" => $v['id'], "type" => 1,]);
                if ($examine) {
                    $goods_list[$k]['examine'] = $examine;
                }
            }

            // if (!empty($v['platform'])) {
            //     $goods_list[$k]['platform'] = is_array(json_decode($v['platform'], true)) ? implode(',', json_decode($v['platform'], true)) : json_decode($v['platform'], true);
            // }

            if (!empty($v['welfare'])) {
                $goods_list[$k]['welfare'] = is_array(json_decode($v['welfare'], true)) ? implode(',', json_decode($v['welfare'], true)) : json_decode($v['welfare'], true);
            }
            $goods_list[$k]['category_id'] = array();
            if (!empty($v['first_category_id'])) {
                array_push($goods_list[$k]['category_id'], $v['first_category_id']);
            }
            if (!empty($v['second_category_id'])) {
                array_push($goods_list[$k]['category_id'], $v['second_category_id']);
            }
            if (!empty($v['third_category_id'])) {
                array_push($goods_list[$k]['category_id'], $v['third_category_id']);
            }
        }

        $data = [
            'list' => $goods_list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $goods_count,
            'more' => $more
        ];
        return $data;

    }

    //记录搜索关键词
    public static function recordKeyWord($keyword, $user_id)
    {
        $record = Db::name('search_record')->where(['user_id' => $user_id, 'keyword' => $keyword, 'del' => 0])->find();

        if ($record) {
            return Db::name('search_record')->where(['id' => $record['id']])->update(['count' => Db::raw('count+1'), 'update_time' => time()]);
        }
        return Db::name('search_record')->insert(['user_id' => $user_id, 'keyword' => $keyword]);
    }

    //商品详情
    public static function getGoodsDetail($user_id, $id)
    {

        $goods = Goods::field("id,name,first_category_id,second_category_id,third_category_id,brand_id,supplier_id,image,remark,create_time,goods_links,platform,welfare,commission,coupon,good_price,click_count,validity,sales,goods_num,production_cycle")
            ->get(['id' => $id]);

        if ($goods) {
            //点击量
            $goods->click_count = $goods->click_count + 1;
            $goods->save();
            $goods->is_collect = 0;

            if ($user_id) {
                //是否收藏
                $collect = Db::name('user_collection')->where(['user_id' => $user_id, 'collection_id' => $id, 'type' => 0])->find();
                $goods->is_collect = $collect ? 1 : 0;
            }
            //猜你喜欢
            $goods->Like();
            //商品规格
//            $goods->GoodsSpec();
//            $goods->append(['comment'])->hidden(['Spec', 'GoodsSpecValue'])->visible(['id', 'name', 'image',  'remark',  'sales', 'click_count', 'good_price', 'is_collect', 'goods_spec', 'goods_image', 'goods_item', 'activity']);

            $goods->append(['comment'])->hidden(['Spec', 'GoodsSpecValue']);
            Db::name('goods_click')->insert([
                'user_id' => $user_id,
                'goods_id' => $id,
                'create_time' => time(),
            ]);

            $goods['create_time'] = date("Y-m-d H:i", $goods['create_time']);
//            $goods['platform'] = $goods['platform'];
            $goods['welfare'] = implode(",", json_decode($goods['welfare'], true));

            $category_id = array();
            if (!empty($goods['first_category_id'])) {
                $category_id[] = $goods['first_category_id'];
            }
            if (!empty($goods['second_category_id'])) {
                $category_id[] = $goods['second_category_id'];
            }
            if (!empty($goods['third_category_id'])) {
                $category_id[] = $goods['third_category_id'];
            }
            $goods['category_id'] = $category_id;
            $goods['validity'] = date("Y-m-d 00:00:00",$goods['validity']);
            $brand_name = Db::name("goods_brand")->field("id,name")->where("id",$goods['brand_id'])->find();
            $goods['brand_name'] = $brand_name ?? "";

            foreach ($goods['like'] as $k => $v) {
                $goods['like'][$k]['create_time'] = date("Y-m-d H:i", $v['create_time']);
                $goods['like'][$k]['platform'] = $v['platform'];
                $goods['like'][$k]['supplier_platform'] = json_decode($v['supplier_platform'], true);
                $goods['like'][$k]['welfare'] = !empty(json_decode($v['welfare'], true)) ? implode(",", json_decode($v['welfare'], true)) : "";
            }
            $goods->toArray();
            $supplier = Db::name("supplier")->field("platform as supplier_platform,store_name,store_url")->where("id", $goods['supplier_id'])->find();
            $goods['supplier'] = [
                'supplier_platform' => !empty(json_decode($supplier['supplier_platform'], true)) ? implode(",", json_decode($supplier['supplier_platform'], true)) : "",
                'store_name' => $supplier['store_name'],
                'store_url' => $supplier['store_url']
            ];
            return $goods;
        }
        return [];

    }

    //好物优选
    public static function getBestList($page, $size)
    {
        $goods = new Goods();
        $goods_count = $goods
            ->where(['del' => 0, 'status' => 2])
            ->count();
        $goods_list = $goods
            ->where(['del' => 0, 'status' => 2])
            ->field('id,name,image,good_price')
            ->order('id desc')
            ->page($page, $size)
            ->select();

        $more = is_more($goods_count, $page, $size);  //是否有下一页

        $data = [
            'list' => $goods_list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $goods_count,
            'more' => $more
        ];
        return $data;
    }

    public static function getHostList($page, $size)
    {
        $goods = new Goods();
        $goods_count = $goods
            ->where(['del' => 0, 'status' => 1])
            ->count();

        $goods_list = $goods
            ->where(['del' => 0, 'status' => 1])
            ->field('id,name,image,good_price,sales_sum+virtual_sales_sum as sales_sum,click_count')
            ->order('sales_sum desc,click_count desc')
            ->page($page, $size)
            ->select();

        $more = is_more($goods_count, $page, $size);  //是否有下一页

        $data = [
            'list' => $goods_list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $goods_count,
            'more' => $more
        ];
        return $data;
    }


    //搜索记录
    public static function getSearchPage($user_id, $limit)
    {
        $history_list = Db::name('search_record')
            ->where(['user_id' => $user_id, 'del' => 0])
            ->limit($limit)
            ->order('id desc')
            ->column('keyword');
        $hot_lists = ConfigServer::get('hot_search', 'hot_keyword', []);
        return [
            'history_lists' => $history_list,
            'hot_lists' => $hot_lists,
        ];
    }


    //清空搜索记录
    public static function clearSearch($user_id)
    {
        return Db::name('search_record')
            ->where(['user_id' => $user_id])
            ->update(['del' => 1, 'update_time' => time()]);

    }

    /**
     * 修改商品状态
     * @param $goods_id
     * @param $supplier_id
     * @param int $status
     * @return false|int|string
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function editStatus($goods_id, $supplier_id, $status = 0)
    {
        $saveData = [
            "status" => $status
        ];
        return Db::name('goods')
            ->where(['id' => $goods_id, 'supplier_id' => $supplier_id])
            ->update($saveData);
    }

    /**
     * 猜你喜欢(取购物车中的商品类别，否则随机取10)
     * @param $user_id
     * @return array|false|mixed|\PDOStatement|string|\think\Collection|Db[]|\think\db\Query[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getGoodsLike($user_id)
    {
        $like_label = Db::name("cart")
            ->alias("c")
            ->leftJoin("goods g", "c.goods_id = g.id")
            ->where("user_id", $user_id)
            ->field("g.first_category_id")
            ->group("g.first_category_id")
            ->column("g.first_category_id");

        $model = new Goods();
        $goods = $model->alias("g")
            ->leftJoin("supplier s", "g.supplier_id=s.id")
            ->field("g.id,name,supplier_id,g.image,g.platform,g.welfare,g.commission,g.coupon,g.good_price,g.click_count,g.sales,g.remark,s.platform as supplier_platform")
            ->where([["g.status", "=", 2], ["g.del", "=", 0]])
            ->limit(10);

        if ($like_label) {
            $goods->where("first_category_id", "in", $like_label);
        }

        $result = $goods->orderRaw('rand()')->select();
        if (!$result) {
            return false;
        }

        foreach ($result as $k => $v) {
            $result[$k]['welfare'] = json_decode($v['welfare'], true);
            $result[$k]['supplier_platform'] = json_decode($v['supplier_platform'], true);
        }
        return $result;
    }

    //获取有效商品ida
    public static function getGoodsIds($goods_ids=[])
    {
        return Db::name('goods')
            ->where(['id' => $goods_ids,'status' => 2])
            ->column('id');
    }
}